﻿Imports System.Windows.Threading

Partial Public Class BubblingEvents

    Private _objRoutedEventHandler As RoutedEventHandler = New RoutedEventHandler(AddressOf outerGrid_MouseUp)
    Private WithEvents _objResetTimer As DispatcherTimer

    Private Sub innerGrid_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles innerGrid.MouseUp
        Me.innerGrid.Background = Brushes.Red
        e.Handled = Me.chkInner.IsChecked.Value
        _objResetTimer.Start()
    End Sub

    Private Sub _objResetTimer_Elapsed(ByVal sender As Object, ByVal e As System.EventArgs) Handles _objResetTimer.Tick
        RestoreColors()
        _objResetTimer.Stop()
    End Sub

    Private Sub RestoreColors()
        Me.outerGrid.Background = Brushes.LightYellow
        Me.middleGrid.Background = Brushes.LightGreen
        Me.innerGrid.Background = Brushes.LightGray
    End Sub

    Private Sub BubblingEvents_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        RestoreColors()
        _objResetTimer = New DispatcherTimer
        _objResetTimer.Interval = New TimeSpan(0, 0, 2)
        Me.outerGrid.AddHandler(Grid.MouseUpEvent, _objRoutedEventHandler)
    End Sub

    Private Sub middleGrid_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles middleGrid.MouseUp
        Me.middleGrid.Background = Brushes.Red
        e.Handled = Me.chkMiddle.IsChecked.Value
        _objResetTimer.Start()
    End Sub

    Private Sub outerGrid_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
        Me.outerGrid.Background = Brushes.Red
        _objResetTimer.Start()
    End Sub

    Private Sub chkOuter_Checked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles chkOuter.Checked
        Me.outerGrid.RemoveHandler(Grid.MouseUpEvent, _objRoutedEventHandler)
        Me.outerGrid.AddHandler(Grid.MouseUpEvent, _objRoutedEventHandler, True)
    End Sub

    Private Sub chkOuter_Unchecked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles chkOuter.Unchecked
        Me.outerGrid.RemoveHandler(Grid.MouseUpEvent, _objRoutedEventHandler)
        Me.outerGrid.AddHandler(Grid.MouseUpEvent, _objRoutedEventHandler)
    End Sub
End Class
